﻿using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ObjectContextMigration
{

    public class ContextMigrator
    {
        /// <summary>
        /// Performs the necessary actions for migrating entities between Object Contexts
        /// </summary>
        public ContextMigrator()
        {
            this.entityComponentsExtractor = new EntityComponentsExtractor();
        }

        private EntityComponentsExtractor entityComponentsExtractor;

        public void MigrateContext(ObjectContext sourceContext, ObjectContext targetContext, EntityObject entity, bool saveChanges, bool removeFromSource) {
            try
            {
                this.MigrateContext(sourceContext, targetContext, entity);
                if (saveChanges)
                {
                    try
                    {
                        targetContext.SaveChanges();

                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
            catch (Exception e)
            {

            }
        }

        private void MigrateContext(ObjectContext sourceContext, ObjectContext targetContext, EntityObject entity)
        {
            List<EntityObject> childEntities = this.entityComponentsExtractor.GetAllDependentEntities(entity);
            sourceContext.Detach(entity);

            targetContext.AddObject(entity.EntityKey.EntitySetName, entity);

            foreach(EntityObject childEntity in childEntities) {
                this.MigrateContext(sourceContext, targetContext, childEntity);
            }
        }

    }
}
